
module(...,package.seeall)

require"misc"
require"mqtt"
require"mqttInMsg"

local sub_topic = "air202/in"

local mqtt_server = "120.79.164.77"
local mqtt_port = 1883

local ready = false

--- MQTT连接是否处于激活状态
-- @return 激活状态返回true，非激活状态返回false
-- @usage mqttTask.isReady()
function isReady()
    return ready
end

sys.taskInit(
    function()
        while true do
            if not socket.isReady() then
                --等待网络环境准备就绪，超时时间是5分钟
                sys.waitUntil("IP_READY_IND",300000)
            end

            if socket.isReady() then
                local clientId = misc.getImei()
                local mqttClient = mqtt.client(clientId,600)
                
                --阻塞执行MQTT CONNECT动作，直至成功
                if mqttClient:connect(mqtt_server,mqtt_port) then
                    read = true

                    --订阅主题
                    if mqttClient:subscribe(sub_topic) then
                        while true do
                            if not mqttInMsg.proc(mqttClient) then 
                                log.error("mqttTask.mqttInMsg.proc error") break 
                            end 
                        end
                    end
                    ready = false
                end
                --断开MQTT连接
                mqttClient:disconnect()
                sys.wait(5000)   
            else
                --进入飞行模式，20秒之后，退出飞行模式
                net.switchFly(true)
                sys.wait(20000)
                net.switchFly(false)
            end
        end
    end
)